<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace WebModule;

use Nette\Object;
use ApplicationsModule\PeopleModule\PeopleManagement;
use Celebrio\AccessControl\UserManagement;
use \ApplicationsModule\PeopleModule\Person;
use \Facebook;

/**
 * Sign In Page presenter.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class FacebookUserManager extends Object
{

    private $people_manager = null;

    public function __construct()
    {
        $this->people_manager = new PeopleManagement();
    }

    public function addUser($user, $params)
    {
        $usersID = array();
        if (array_key_exists("state", $params)) {
            $usersID = explode(",", $params["state"]);
        }
        $fb_uid = $user["id"];
        foreach ($usersID as $id) {
            $exists = $this->checkExisting($id, $fb_uid);
            if ($exists) {
                continue;
            } else {
                $uid = $user["id"];
                $person = new Person();
                $person->setUserId($id);
                $person->setFirstName($user["first_name"]);
                $person->setLastName($user["last_name"]);
                $person->setProfilePicture("http://graph.facebook.com/$uid/picture?type=large");
                $person->addToAdditionalInfo("uid", $uid);
                $person->addToAdditionalInfo("code", $params["code"]);
                $person->addToAdditionalInfo("access_token", $params["access_token"]);
                $this->people_manager->createPerson($person, false, false);
            }
        }
    }

    public function registerUserFacebook($user, $params) {
        $person = $this->people_manager->getPerson();
        $info = $person->getAdditionalInfo();
        if(isset($info["uid"])) {
            return true;
        } else {
            $person->addToAdditionalInfo("uid", $user["id"]);
            $person->addToAdditionalInfo("code", $params["code"]);
            $person->addToAdditionalInfo("access_token", $params["access_token"]);
            $this->people_manager->updatePerson("uid", $person);
        }
    }

    /**
     * Checks if users are already connected
     * NOTE: Sets admin mode in PeopleManagement!
     *
     * @param $userId of Celebrio user
     * @return bool true if user is already connected, false otherwise
     */
    public function checkExisting($userId, $fb_uid)
    {
        $pm = $this->people_manager;
        $person = $pm->getPerson($userId);
        $pm->setAdminMode(true);
        $contacts = $pm->getContactsWith("uid", $person->getId());
        foreach ($contacts as $contact) {
            $info = $contact->getAdditionalInfo();
            $c_uid = $info["uid"][0];
            if ($c_uid == $fb_uid) {
                return true;
            }
        }
        return false;
    }
}